package com.antd.common.sms.util;

import cn.hutool.crypto.digest.MD5;
import cn.hutool.http.ContentType;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.antd.admin.api.entity.SysSmsLog;
import com.antd.common.sms.constant.SmsConstant;
import com.antd.common.sms.enums.SmsTemplateEnum;
import com.antd.common.sms.event.SmsLogEvent;
import com.google.common.collect.Maps;
import lombok.AllArgsConstructor;
import lombok.experimental.UtilityClass;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.HashMap;

/**
 * TODO
 *
 * @author 子丶沫
 * @version 1.0
 * @date 2020/12/2 10:53
 */
@AllArgsConstructor
public class SmsSendService {

    private final ApplicationEventPublisher publisher;

    public String sendSms(String mobile, SmsTemplateEnum smsTemplateEnum, String params){
        HashMap<String, Object> param = Maps.newHashMap();
        param.put("accountSid", SmsConstant.ACCOUNT_SID);
        param.put("templateid",smsTemplateEnum.getValue());
        param.put("to",mobile);
        param.put("timestamp",System.currentTimeMillis());
        param.put("sig",sign());
        String post = HttpUtil.post(SmsConstant.SMS_URL, param);
        JSONObject data = JSON.parseObject(post);
        SysSmsLog log=new SysSmsLog();
        log.setMobile(mobile);
        log.setSendTime(LocalDateTime.now());
        log.setContent(params);
        log.setTemplateName(smsTemplateEnum.getName());
        log.setCreateTime(LocalDateTime.now());
        if(data.getInteger(SmsConstant.SUCCESS_KEY).equals(SmsConstant.SUCCESS_CODE)){
            log.setStatus(0);
            log.setDesc("发送成功");
        }else{
            log.setDesc(data.getString(SmsConstant.SUCCESS_DESC));
            log.setStatus(1);
        }
        publisher.publishEvent(new SmsLogEvent(log));
        return data.getString(SmsConstant.SUCCESS_KEY);
    }
    private static String sign(){
        String signValue=SmsConstant.ACCOUNT_SID+SmsConstant.AUTH_TOKEN+System.currentTimeMillis();
        String digestHex = MD5.create().digestHex(signValue.getBytes());
        return digestHex;
    }
}
